<template>
     <div class="card" style="height: 80vh">
        <div  class="font-semibold text-xl mb-4">文件库</div>
    <div class="flex justify-between">
      <Breadcrumb :model="navPath">
        <template #item="{ item }">
          <a @click="gotoBack(item)" class="cursor-pointer">{{ item.path }}</a>
        </template>
      </Breadcrumb>
      <div class="flex">
        <Button label="创建目录" class="m-2" @click="() => visibleCreateDir = true"></Button>
        <FileUpload
            chooseLabel="上传文件"
            class="m-2"
            mode="basic"
            name="file"
            :auto="true"
            :withCredentials="true"
            @before-send="fileUploadBefore"
            @upload="refresh"
            :url="'/api/v1/file-manager/upload?raw_path=' + get_path().join('/')"
        >
        </FileUpload>

      </div>
    </div>

    <DataTable :value="data?.data.list" tableStyle="min-width: 50rem" @row-click="(e) => goto(e.data.name)" scrollable scrollHeight="65vh">
      <Column field="name" header="名称">
        <template #body="slotProps">
          <i v-if="slotProps.data.is_dir" class="pi pi-folder" style="color: #54aeff"></i>
          <i v-else class="pi pi-file"></i>
          <span class="ml-2">{{ slotProps.data.name }}</span>
        </template>
      </Column>
      <Column field="size" header="大小"></Column>
      <Column field="mtime" header="修改时间"></Column>
      <Column field="quantity" header="操作" :headerStyle="{width: '200px'}">
        <template #body="slotProps">
          <SplitButton label="下载" :model="items" severity="secondary"
                       @click="() => downloadFile(slotProps.data.name)">
            <template #item="{ item,label, props }">
              <a @click="() => handleMenuClick(item, slotProps.data.name)" v-bind="props.action">{{ label }}</a>
            </template>
          </SplitButton>
        </template>
      </Column>
    </DataTable>
  </div>
  <Dialog v-model:visible="visibleCreateDir" modal header="创建目录" :style="{ width: '25rem' }">
    <form @submit.prevent='onCreateDir'>
      <div class="flex align-items-center gap-3 mt-1">
        <label class="font-semibold w-6rem">目录名称</label>
        <div>
          <InputText id="dirname" v-model="dirname" class="flex-auto" autocomplete="off"/>
          <small class="p-error">{{ errorsDir.dirname }}</small>
        </div>
      </div>

      <div class="flex justify-end gap-2 mt-3">
        <Button type="button" label="取消" severity="secondary" @click="visibleCreateDir = false"></Button>
        <Button type="submit" label="创建"></Button>
      </div>
    </form>
  </Dialog>

  <Dialog v-model:visible="visibleRename" modal header="重命名" :style="{ width: '25rem' }">
    <form @submit.prevent='onRename'>
      <div class="flex align-items-center gap-3 mb-5">
        <label class="font-semibold w-6rem">新名称</label>
        <div>
          <InputText id="newName" v-model="newName" class="flex-auto" autocomplete="off"/>
          <small class="p-error">{{ errorsDir.newName }}</small>
        </div>
      </div>
      <div class="flex justify-content-end gap-2">
        <Button type="button" label="取消" severity="secondary" @click="visibleRename = false"></Button>
        <Button type="submit" label="保存"></Button>
      </div>
    </form>
  </Dialog>
  <ConfirmDialog></ConfirmDialog>
</template>ConfirmDialog
<script setup>
import {useRequest} from 'ahooks-vue';
import {createVNode, h, ref} from "vue";
import {ApiFileDir, ApiMkdir, ApiRemove, ApiRename} from "@/api/FileLibrary.js";
import storage from "store";
import {ACCESS_TOKEN} from "@/store/mutation-types.js";
import axios from "axios";
import router from "@/router.js";
import {useToast} from "primevue/usetoast";
import {useConfirm} from "primevue/useconfirm";
import ConfirmDialog from 'primevue/confirmdialog';
import * as yup from "yup";
import {useForm} from "vee-validate";


const toast = useToast();
const confirm = useConfirm();

const props = defineProps({
  selectFile: Function,
})


const mkdirRef = ref()
const uploadLoading = ref(false)
const navPath = ref([])
const selectIndex = ref(null)
const visibleRename = ref(false)
const visibleCreateDir = ref(false)


const menu = ref();

const items = [
  {
    label: '重命名',
    command: (e, a) => {
      console.log(e)
      console.log(a)
    }
  },
  {
    label: '删除',
  },
];

let oriName = ''

const {data, run, loading, refresh} = useRequest(ApiFileDir, {
  defaultParams: [{dir: ['/']}],
  onSuccess: (e) => setPath(e)
})

function setPath(values) {
  console.log(values)
  let tmpPath = []
  values.data.dir.forEach((item, index) => {
    tmpPath.push({
      path: item,
      breadcrumbName: item,
    })
  })
  navPath.value = tmpPath
}

function dblclick(name) {
  const path = get_path()
  path.push(name)
  props.selectFile(path)
}

function gotoBack(data) {
  const index = navPath.value.indexOf(data)
  if (index + 1 === navPath.value.length) return

  navPath.value.splice(index + 1)
  const raw_path = []
  navPath.value.forEach(item => {
    raw_path.push(item.path)
  })
  run({dir: raw_path})
}

const toggle = (event) => {
  menu.value.toggle(event);
};

function goto(name) {
  const raw_path = []
  navPath.value.forEach(item => {
    raw_path.push(item['path'])
  })
  raw_path.push(name)
  run({dir: raw_path})
}


function get_path() {
  const raw_path = []
  navPath.value.forEach(item => {
    raw_path.push(item.path)
  })
  return raw_path
}


function updateChange(info) {
  if (info.file.status === 'uploading') {
    uploadLoading.value = true
  } else if (info.file.status === 'done') {
    message.success("文件上传完成")
    refresh()
    uploadLoading.value = false
  }
}

const handleMenuClick = async (e, filename) => {
  if (e.label === '删除') {
    confirm.require({
      message: '确认删除该文件吗？',
      header: '系统提示',
      icon: 'pi pi-info-circle',
      rejectProps: {
        label: '取消',
        severity: 'secondary',
        outlined: true
      },
      acceptProps: {
        label: '删除',
        severity: 'danger'
      },
      accept: async () => {
        const result = await ApiRemove({dirname: filename, path: get_path()})
        if (result.code === 0) {
          toast.add({severity: 'success', summary: '成功', detail: '删除成功', life: 3000});
          refresh()
        } else {
          toast.add({severity: 'danger', summary: '错误', detail: result.msg, life: 3000});
        }
      },
    });
  } else if (e.label === '重命名') {
    newName.value = filename
    oriName = filename
    visibleRename.value = true
  } else if (e.key === 'open') {
    // const pathList = get_path()
    // if (pathList[pathList.length - 1] !== '/') {
    //   pathList.push('/')
    // }
    // const filename = data.value.data.list[selectIndex.value]['name']
    // const raw_path = pathList.join('/') + filename
    //
    // let routeData = router.resolve({name: 'office', query: {filePath: encodeURIComponent(raw_path)}});
    // window.open(routeData.href, '_blank');
  }
}


const downloadFile = (filename) => {
  // const filename = data.value.data.list[selectIndex.value]['name']
  const token = storage.get(ACCESS_TOKEN)
  const pathList = get_path()
  const raw_path = pathList.join('/') + filename
  axios.get('/api/v1/file-manager/download?raw_path=' + raw_path, {
    responseType: 'blob',
    headers: {Authorization: 'Bearer ' + token}
  })
      .then(response => {
        // 创建一个临时的URL对象
        const url = window.URL.createObjectURL(new Blob([response.data]));
        // 创建一个下载链接
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filename);
        // 将链接添加到页面并触发点击事件
        document.body.appendChild(link);
        link.click();
        // 清理临时URL对象
        window.URL.revokeObjectURL(url);

      })
}
const fileUploadBefore = (request) => {
  const token = storage.get(ACCESS_TOKEN)
  request.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
  return request
}

// const fileUploadBefore11= () => {
//   alert(1)
//   // const token = storage.get(ACCESS_TOKEN)
//   // request.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
//   // return request
// }

let createDirSchema = yup.object().shape({
  dirname: yup.string().max(20, '字符长度过多').required('请输入目录名称'),
});
const {defineField: defineFieldDir, handleSubmit: handleSubmitDir, errors: errorsDir} = useForm({
  validationSchema: createDirSchema,
});
const [dirname] = defineFieldDir('dirname');


let renameSchema = yup.object().shape({
  newName: yup.string().max(20, '字符长度过多').required('请输入目录名称'),
});
const {defineField: defineFieldRename, handleSubmit: handleSubmitRename, errors: errorsRename} = useForm({
  validationSchema: renameSchema,
});
const [newName] = defineFieldRename('newName');


const onCreateDir = handleSubmitDir(async (values) => {
  const result = await ApiMkdir({...values, path: get_path()})
  if (result.code === 0) {
    toast.add({severity: 'success', summary: '成功', detail: '创建成功', life: 3000});
    refresh()
    visibleCreateDir.value = false
  } else {
    toast.add({severity: 'danger', summary: '失败', detail: '创建失败', life: 3000});
  }
})

const onRename = handleSubmitRename(async (values) => {
  const pathList = get_path()
  const raw_path = pathList.join('/') + oriName
  const result = await ApiRename({raw_file_path: raw_path, new_name: newName.value})
  if (result.code === 0) {
    toast.add({severity: 'success', summary: '成功', detail: '重命名成功', life: 3000});
    refresh()
    visibleRename.value = false
  } else {
    toast.add({severity: 'danger', summary: '失败', detail: '重命名失败', life: 3000});
  }
})
</script>
